﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboPlus.Common;
using WeiboPlus.Models;
using WeiboPlus.Service;
using WeiboPlus.Sina;
using WeiboPlus.Tencent;

namespace WeiboPlus.Shell.Views
{
    public partial class AuthPage : PhoneApplicationPage
    {
        SNSAccount _account;
        private bool hasInit = false;
        public AuthPage()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(AuthPage_Loaded);

            
        }

        void AuthPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (hasInit)
                return;
            hasInit = true;
            //_brower.Navigate(new Uri(AccountManager.Current.GetAllAccount().Where(a=>a.ServiceProvider==SNSProviderType.Sina).FirstOrDefault().AuthorizeURL, UriKind.Absolute));
            //_brower.Navigate(new Uri(AccountManager.Current.GetAllAccount().Where(a => a.ServiceProvider == SNSProviderType.Tencent).FirstOrDefault().AuthorizeURL, UriKind.Absolute));

            if (NavigationContext.QueryString.ContainsKey("accountid"))
            {
                int id;
                var tryOk = int.TryParse(NavigationContext.QueryString["accountid"], out id);
                if (!tryOk)
                {
                    return;
                    //TO-DO : throw error?
                }
                _account = AccountManager.Current.GetAccount(id);
                _brower.Navigate(new Uri(_account.AuthorizeURL, UriKind.Absolute));

            }

            _brower.Navigating += (s, arg) => { urlTextbox.Text = arg.Uri.AbsoluteUri; };

            InitButton();
            //_brower.Navigate(new Uri(AccountManager.Current.GetAllAccount().Where(a => a.ServiceProvider == SNSProviderType.Sina).FirstOrDefault().AuthorizeURL, UriKind.Absolute));
            //throw new NotImplementedException();
        }

        private void InitButton()
        {
            var button = new ApplicationBarIconButton(new Uri("/Images/AppBarIcons/appbar.check.rest.png", UriKind.Relative)) { Text = AppResx.ButtonConnectText };
            button.Click += new EventHandler(button_Click);

            ApplicationBar.Buttons.Add(button);
            //throw new NotImplementedException();
        }

        private void button_Click(object sender, EventArgs e)
        {
            var pin = Clipboard.GetText();
            if (string.IsNullOrEmpty(pin.Trim()))
            {
                MessageBox.Show(AppResx.GetPinAlertText, AppResx.GetPinAlertTitleText, MessageBoxButton.OK);
                return;
            }

            var reg = new Regex("(\\d{6})");

            Match match = reg.Match(pin);

            if (match.Success)
            {
                AccessToken();
            }
            else
            {
                MessageBox.Show(AppResx.GetPinAlertText, AppResx.GetPinAlertTitleText, MessageBoxButton.OK);
            }

        }

        private void _brower_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_account.ServiceProvider == SNSProviderType.RenRen)
            {
                var url = e.Uri.ToString();
                if (url.Contains("code="))
                {
                    var code = url.Substring(url.LastIndexOf("?code=") + 6);
                    _account.PIN = code;
                    goto LABEL_ACCESS_TOKEN;
                }
                goto LABEL_RETURN;
            }

            if (_account.ServiceProvider == SNSProviderType.Tencent)
            {
                var url = e.Uri.ToString();
                if (url.Contains("v="))
                {
                    var code = url.Substring(url.LastIndexOf("v=") + 2);
                    _account.PIN = code;
                    goto LABEL_ACCESS_TOKEN;
                }
                goto LABEL_RETURN;
            }

            string responseText = _brower.SaveToString();
            Regex reg;
            switch (_account.ServiceProvider)
            {
                case SNSProviderType.Sina:
                    {
                        reg = new Regex(">(\\d{6})<");
                        break;
                    }
                //case SNSProviderType.RenRen:
                default:
                    reg = new Regex("授权码：(\\d{6})");
                    break;
            }


            Match match = reg.Match(responseText);

            if (match.Success)
            {
                string veryfier = match.Groups[1].Value;
                _account.PIN = veryfier;

                goto LABEL_ACCESS_TOKEN;
            }

        LABEL_RETURN:
            return;

        LABEL_ACCESS_TOKEN:
            AccessToken();

        }

        private void AccessToken()
        {
            IOAuthService service = PhoneApplicationController.Current.Container.Resolve<IOAuthService>(_account.ServiceProvider.ToString());

            if (service.Account == null)
            {
                service.ProviderResolver = () => SNSProviderManager.GetFactory(_account).GetProvider();
                service.FactoryResolver = () => SNSProviderManager.CreateFactory(_account);
                service.Account = _account;
            }

            service.AccessToken((_acount, res) =>
            {
                if (!res.IsSuccess)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show(res.Message);
                        if (NavigationService.CanGoBack)
                            NavigationService.GoBack();
                    });
                }
                else
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        NavigationService.Navigate(new Uri("/Views/MainView.xaml", UriKind.RelativeOrAbsolute));
                    });
                }
            });
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            AccountManager.Current.Remove((account) => { return !account.IsBind || account.IsDuplicate; });
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (PhoneApplicationController.Current.AppSetting.EnableOrientationChange)
            {
                SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
            }
            else
            {
                var orientation = (SupportedPageOrientation)PhoneApplicationController.Current.AppSetting.CurrentSupportedOrientation;
                this.SupportedOrientations = orientation;
                this.Orientation = (PageOrientation)PhoneApplicationController.Current.AppSetting.CurrentOrientation;
            }
        }

        
    }
}
